package conchmusic.conchmusicclient.popupWindow;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import conchmusic.conchmusicclient.R;
import conchmusic.conchmusicclient.dao.ClientControl;
import conchmusic.conchmusicclient.dao.MyDBHelp;
import conchmusic.conchmusicclient.pojo.Song;
import conchmusic.conchmusicclient.pojo.SongList;
import conchmusic.conchmusicclient.pojo.User;
import conchmusic.conchmusicclient.thread.InsertSongToSonglistThread;
import conchmusic.conchmusicclient.thread.OnlineThread;
import conchmusic.conchmusicclient.util.InitPlayBar;
import conchmusic.conchmusicclient.view.PlayBar;

/**
 * Created by Administrator on 2017/4/23.
 */

public class OnlinePopupWindow extends PopupWindow {
    private View mMenuView;
    private Button download;
    private Button nextSong;
    private Button cancel;
    private Button insertSongList;
    private int songPosition;
    private BaseAdapter listViewAdapter;
    private Context context;
    private List<Song> listItems;
    private Thread thread;
    private Dialog insertSonglistdialog;
    private ListView insertSongListView;
    private ArrayAdapter<String> songlistAdapter;
    private ArrayList<String> songlistname;
    private List<SongList> songLists;;
    private int uid;
    private InsertSongToSonglistThread insertSongToSonglist;
    private Handler handler;
    private ClientControl clientControl;
    private MyDBHelp myDBHelp;
    private Handler downSongHandler;
    private ProgressBar progressBar;
    private InitPlayBar initPlayBar;
    private PlayBar playBar;
    private Button btn_play;
    private Handler updateSongHandler;
    private User user;

    public OnlinePopupWindow(BaseAdapter listViewAdapter, final Activity context, final int position, List<Song> listItems, final ProgressBar progressBar) {
        super(context);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.online_popup_window, null);
        this.listItems = listItems;
        this.songPosition = position;
        this.listViewAdapter = listViewAdapter;
        this.context = context;
        //注意得到uid;
        btn_play=(Button)context.findViewById(R.id.playbar_play);
        playBar=(PlayBar)context.findViewById(R.id.local_search_playbar);
        initPlayBar=new InitPlayBar(playBar,context);
        this.progressBar=progressBar;
        myDBHelp=new MyDBHelp(context,"demon",null,1);
        clientControl=new ClientControl(myDBHelp);
        user=clientControl.Login();

        songlistname=new ArrayList<>();
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:
                        Toast.makeText(context,"远程插入失败",Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(context,"本地插入失败",Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        Toast.makeText(context,"插入成功",Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };

        downSongHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 4:
                        Toast.makeText(context,"下载成功",Toast.LENGTH_SHORT).show();
                        break;
                    case 5:
                        Toast.makeText(context,"下载失败",Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
        insertSongList=(Button)mMenuView.findViewById(R.id.online_insert_songlist) ;
        download = (Button) mMenuView.findViewById(R.id.download_music_button);
        nextSong = (Button) mMenuView.findViewById(R.id.online_nextSong);
        cancel = (Button) mMenuView.findViewById(R.id.online_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //销毁弹出框
                dismiss();
            }
        });
        download.setOnClickListener(itemsOnClick);
        nextSong.setOnClickListener(itemsOnClick);
        insertSongList.setOnClickListener(itemsOnClick);
        this.setContentView(mMenuView);
        this.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        this.setBackgroundDrawable(dw);
        mMenuView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = mMenuView.findViewById(R.id.online_pop_layout).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            dismiss();
            switch (v.getId()) {
                case R.id.online_nextSong:
                    initPlayBar.itemInitPlaybar();
                    String[] list=new String[listItems.size()];
                    for(Song song:listItems){
                        clientControl.addSong(song);
                    }
                    for(int i=0;i<listItems.size();i++){
                        Song onlineSong=clientControl.findCloudSong(listItems.get(i));
                        list[i]=Integer.toString(onlineSong.getLocalSongId());
                    }
                    btn_play.setBackgroundResource(R.mipmap.ic_pause);
                    Intent intent=new Intent();
                    intent.putExtra("action","play");
                    intent.putExtra("posit",songPosition);
                    intent.putExtra("songList",list);
                    intent.setAction("music2");
                    intent.setPackage(context.getPackageName());
                    context.startService(intent);
                    //播放下一首
                    break;
                case R.id.download_music_button:
                    Song downSong=new Song();
                    downSong=listItems.get(songPosition);
                    List<Song> songsDown=clientControl.findSongs(2);
                    boolean flag=false;
                    for(Song song:songsDown) {
                        if (song.getSongId() == downSong.getSongId()) {
                            Toast.makeText(context, "本地已下载", Toast.LENGTH_SHORT).show();
                            flag=true;
                        }
                    }
                    if(!flag){
                        Log.i("OnlinePopu188",downSong.getSongUrl());
                        OnlineThread onlineThread = new OnlineThread(downSong, context, downSongHandler);
                        thread = new Thread(onlineThread);
                        thread.start();
                    }
                    break;
                case R.id.online_insert_songlist:
//                    try {
//                        try {
//                            Method method=context.getClass().getMethod("getUid");
//                            uid=(int)method.invoke((Object)context);
//                            Log.i("uid",Integer.toString(uid));
//                        } catch (IllegalAccessException e) {
//                            e.printStackTrace();
//                        } catch (InvocationTargetException e) {
//                            e.printStackTrace();
//                        }
//                    } catch (NoSuchMethodException e) {
//                        e.printStackTrace();
                    if(user==null){
                        Toast.makeText(context,"请登录",Toast.LENGTH_SHORT).show();
                    }else{
                        uid=user.getUserId();
                        insertSonglistdialog=new AlertDialog.Builder(context).create();
                        insertSonglistdialog.show();
                        insertSonglistdialog.getWindow().setContentView(R.layout.insert_to_songlist_popup);
                        WindowManager.LayoutParams params = insertSonglistdialog.getWindow().getAttributes();
                        WindowManager windowManager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
                        int width = windowManager.getDefaultDisplay().getWidth();//屏幕宽度
                        int height = windowManager.getDefaultDisplay().getHeight();
                        params.width = (int)(width*0.8);
                        params.height = (int)(height*0.4);
                        insertSonglistdialog.getWindow().setAttributes(params);
                        insertSongListView=(ListView)insertSonglistdialog.getWindow().findViewById(R.id.insert_to_songlist_listView);
                        //根据用户名通过数据库得到歌单信息
                        songLists=clientControl.getSongLists(uid);
                        for(SongList songList:songLists){
                            songlistname.add(songList.getSongListName());
                        }
                        songlistAdapter=new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1,songlistname);
                        insertSongListView.setAdapter(songlistAdapter);
                        insertSongListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                SongList clickSonglist=new SongList();
                                clickSonglist=songLists.get(position);
                                Song song=new Song();
                                song=listItems.get(songPosition);
                                List<Song> findList=clientControl.findSongs(clickSonglist.getSongListId());
                                for(Song songInList:findList){
                                    if(songInList.getSongId()==song.getSongId()) {
                                        Toast.makeText(context,"歌曲已存在",Toast.LENGTH_SHORT).show();
                                        insertSonglistdialog.cancel();
                                        return;
                                    }
                                }
                                insertSongToSonglist=new InsertSongToSonglistThread(clickSonglist.getSongListId(),song.getSongId(),context,uid,handler);
                                Thread insertThread=new Thread(insertSongToSonglist);
                                insertThread.start();
                                insertSonglistdialog.cancel();
                            }
                        });
                    }

                    break;
                default:

                    break;
            }

        }

    };


}
